package com.warm.pom.satoken.utils;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.warm.core.constant.HttpStatus;
import com.warm.core.exception.ServiceException;
import com.warm.system.api.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 安全服务工具类
 *
 * @author warm
 */
public class LoginUtils {

    private static final Logger log = LoggerFactory.getLogger(LoginUtils.class);

    public static final String LOGIN_USER = "LOGIN_USER";

    public static void setLoginUser(LoginUser loginUser) {
        StpUtil.getTokenSession().set(LOGIN_USER, loginUser);
    }

    /**
     * 用户ID
     **/
    public static Long getUserId() {
        try {
            return getLoginUser().getUserId();
        } catch (Exception e) {
            throw new ServiceException("获取用户ID异常" , HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取部门ID
     **/
    public static Long getDeptId() {
        try {
            return getLoginUser().getDeptId();
        } catch (Exception e) {
            throw new ServiceException("获取部门ID异常" , HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户账户, 不抛异常
     **/
    public static String getUsernameNe() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            log.warn("获取用户账户异常");
            return null;
        }
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            throw new ServiceException("获取用户账户异常" , HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        return (LoginUser) StpUtil.getTokenSession().get(LOGIN_USER);
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        return BCrypt.hashpw(password);

    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        return BCrypt.checkpw(rawPassword, encodedPassword);
    }


    /**
     * 通过用户id是否为管理员
     *
     * @param userId 用户id
     * @return 结果
     */
    public static boolean isAdminU(Long userId) {
        return userId != null && 1L == userId;
    }

    /**
     * 通过角色id是否为管理员
     *
     * @param roleId 角色id
     * @return 结果
     */
    public static boolean isAdminR(Long roleId) {
        return roleId != null && 1L == roleId;
    }
}
